import {
  createRouter,
  createWebHashHistory,
  createWebHistory,
} from "vue-router";
import store from "../store/index.js";

const routes = [
  // {
  //   path: "/",
  //   name: "home", //页面的name
  //   component: HomeView,
  // },
  {
    path: "/login",
    name: "login",
    component: () => import("../views/pages/login.vue"),
  },
  {
    path: "/",
    name: "layout",
    component: () => import("../views/Layout/Layout.vue"), // 懒加载 进入该组件才引入
    // 重定向
    redirect: "/index",
    children: [
      {
        path: "/index",
        name: "index",
        component: () => import("../views/pages/index.vue"),
      },
      {
        path: "/roles",
        name: "rolesList",
        component: () => import("../views/pages/rolesList.vue"),
      },
      {
        path: "/user",
        name: "userList",
        component: () => import("../views/pages/userList.vue"),
      },
      {
        path: "/goods",
        name: "goodsList",
        component: () => import("../views/pages/goodsList.vue"),
      },
    ],
  },
];

const router = createRouter({
  // 使用hash
  // history: createWebHashHistory()，
  history: createWebHistory(process.env.BASE_URL),
  routes,
});

// 路由守卫
router.beforeEach((to, from, next) => {
  // 判断用户是否登录
  console.log("store", store.state.userinfo);
  const userinfo = store.state.userinfo.userinfo;
  if (!userinfo) {
    console.log("用户未登录！");
    if (to.path === "/login") {
      next();
      return;
    }
    // 回到登录页
    next("/login");
  } else {
    // 页面随便跳转
    // 一定要加上下面这句话
    next();
  }
});
export default router;
